package mes.kanban.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;

/**
 * 全局异常处理
 * 
 * Shiro框架会根据用户登录及权限状态抛出异常，建议使用SpringMVC的全局异常捕获来处理异常，避免重复代码
 * 
 * @author gjy
 *
 *         2018年2月28日上午10:12:48
 */
public class MyExceptionHandler implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		ModelAndView mv = new ModelAndView();
		FastJsonJsonView view = new FastJsonJsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		if (ex instanceof UnauthenticatedException) {
			attributes.put("code", "10010");
			attributes.put("msg", "token错误");
		} else if (ex instanceof UnauthorizedException) {
			attributes.put("code", "10000");
			attributes.put("msg", "用户无权限");
		} else {
			attributes.put("code", "10086");
			attributes.put("msg", ex.getMessage());
		}

		view.setAttributesMap(attributes);
		mv.setView(view);
		return mv;

	}

}
